<template>
    <div class="permission-list">
        <div class="toolbar">
            <el-button type="primary" @click="handleAdd">新增权限</el-button>
        </div>

        <el-table
            :data="treeData"
            style="width: 100%"
            v-loading="loading"
            row-key="uUID"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        >
            <el-table-column prop="permissionName" label="权限名称" />
            <el-table-column prop="code" label="权限编码" />
            <el-table-column prop="permissionSlot" label="排序" width="100" />
            <el-table-column prop="updateTime" label="更新时间" width="180" />
            <el-table-column label="操作" width="150" fixed="right">
                <template #default="{ row }">
                    <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
                    <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <permission-form
            v-model="dialogVisible"
            :type="dialogType"
            :permission-data="currentPermission"
            :permission-list="permissionList"
            @success="handleSuccess"
        />
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { List as GetList, Delete, details, type UserPermission } from '@/apis/permission'
import PermissionForm from './PermissionForm.vue'

// 状态变量
const loading = ref(false)
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const currentPermission = ref<UserPermission>()
const permissionList = ref<UserPermission[]>([])

// 转换为树状结构
const treeData = computed(() => {
    const list = [...permissionList.value].sort((a, b) => a.permissionSlot - b.permissionSlot)
    const map = new Map<string, UserPermission & { children?: UserPermission[] }>()
    const tree: (UserPermission & { children?: UserPermission[] })[] = []

    // 创建映射
    list.forEach(item => {
        map.set(item.uUID, { ...item })
    })

    // 构建树
    list.forEach(item => {
        const node = map.get(item.uUID)!
        if (item.parentUUID) {
            const parent = map.get(item.parentUUID)
            if (parent) {
                parent.children = parent.children || []
                parent.children.push(node)
            } else {
                tree.push(node)
            }
        } else {
            tree.push(node)
        }
    })

    // 对每个节点的子节点进行排序
    const sortChildren = (nodes: (UserPermission & { children?: UserPermission[] })[]) => {
        nodes.forEach(node => {
            if (node.children && node.children.length > 0) {
                node.children.sort((a, b) => a.permissionSlot - b.permissionSlot)
                sortChildren(node.children)
            }
        })
    }
    sortChildren(tree)

    return tree
})

// 获取权限列表
const fetchList = async () => {
    loading.value = true
    try {
        const data = await GetList({
            keyword: ''
        })
        permissionList.value = data.list
    } catch (error) {
        console.error('获取权限列表失败:', error)
        ElMessage.error('获取权限列表失败')
    } finally {
        loading.value = false
    }
}

// 新增权限
const handleAdd = () => {
    dialogType.value = 'add'
    currentPermission.value = undefined
    dialogVisible.value = true
}

// 编辑权限
const handleEdit = async (row: UserPermission) => {
    dialogType.value = 'edit'
    try {
        const detail = await details(row.uUID)
        currentPermission.value = detail
        dialogVisible.value = true
    } catch (error) {
        console.error('获取权限详情失败:', error)
        ElMessage.error('获取权限详情失败')
    }
}

// 删除权限
const handleDelete = async (row: UserPermission) => {
    try {
        await ElMessageBox.confirm('确定要删除该权限吗？', '提示', {
            type: 'warning'
        })
        await Delete(row.uUID)
        ElMessage.success('删除成功')
        fetchList()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除失败:', error)
            ElMessage.error('删除失败')
        }
    }
}

// 操作成功回调
const handleSuccess = () => {
    fetchList()
}

// 初始化
onMounted(() => {
    fetchList()
})
</script>

<style scoped lang="scss">
.permission-list {
    .toolbar {
        margin-bottom: 16px;
    }
}
</style> 